#include "graphics.h"

Graphics::Graphics(QWidget *parent)
	: QWidget(parent)
	, secondsToShow(4.0)
	, maxValueToShow(2.0)
{
	setBackgroundRole(QPalette::Base);
    setAutoFillBackground(true);

	startTimer(50);
}

Graphics::~Graphics()
{

}

QSize Graphics::minimumSizeHint() const
{
    return QSize(300, 300);
}

QSize Graphics::sizeHint() const
{
    return QSize(300, 300);
}

int Graphics::heightForWidth (int w) const
{
	return w;
}

void Graphics::addValue(const GraphicData& data)
{
	graphicData.push_back(data);

	if(secondsToShow < data.time)
		secondsToShow = data.time;

	double maxValue = fabs(data.angleVel) > fabs(data.vel) ? fabs(data.angleVel) : fabs(data.vel);
	maxValue = maxValue > fabs(data.drift) ? maxValue : fabs(data.drift);

	if(maxValueToShow < maxValue)
		maxValueToShow = maxValue;
}

void Graphics::paintEvent(QPaintEvent *event)
{
	if(graphicData.size() < 2)
		return;

	int pixInSecond = width() / secondsToShow;
	int pixInValue = height() / 2.0 / maxValueToShow;

	QPainterPath angleVel;
	QPainterPath vel;
	QPainterPath drift;
	angleVel.moveTo(graphicData[0].time*pixInSecond, height()/2.0-graphicData[0].angleVel*pixInValue);
	vel.moveTo(graphicData[0].time*pixInSecond, height()/2.0-graphicData[0].vel*pixInValue);
	drift.moveTo(graphicData[0].time*pixInSecond, height()/2.0-graphicData[0].drift*pixInValue);

	for(int i = 1; i != graphicData.size(); ++i)
	{
		angleVel.lineTo(graphicData[i].time*pixInSecond, height()/2.0-graphicData[i].angleVel*pixInValue);
		vel.lineTo(graphicData[i].time*pixInSecond, height()/2.0-graphicData[i].vel*pixInValue);
		drift.lineTo(graphicData[i].time*pixInSecond, height()/2.0-graphicData[i].drift*pixInValue);
	}

	QPainter painter(this);
	
	QPen pen(1);
	painter.setPen(pen);
	painter.drawLine(0, height()/2, width(), height()/2);

	painter.setRenderHint(QPainter::Antialiasing, true);

	pen.setWidth(3);
	pen.setColor(Qt::blue);
	painter.setPen(pen);
	painter.drawPath(angleVel);
	painter.setFont(QFont("Arial", 20));
	painter.drawText(10,25,QChar(937));

	pen.setColor(Qt::red);
	painter.setPen(pen);
	painter.drawPath(vel);
	painter.drawText(30,25,QChar('V'));

	pen.setColor(Qt::green);
	painter.setPen(pen);
	painter.drawPath(drift);
	painter.drawText(50,25,QChar(946));
}

void Graphics::timerEvent(QTimerEvent *event)
{
	update();
}